//
//  TMJsonParser.m
//  TelethonMobile
//
//  Created by Cyril ALIX on 03/12/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "TMServerApi.h"

static TMServerApi* sharedInstance;
static NSMutableData* responseData;

@implementation TMServerApi

@synthesize delegate;

- (id)init
{
    self = [super init];
    if (self) {    }
    return self;
}

- (void) fetchLocationsWithDistance:(float)distance andLongitude:(float)longitude andLatitude:(float)latitude filterByCategory:(int)categorie andDelegate:(id)sender
{
    self.delegate = sender;
    
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:URL_LIEUX_PAR_CATEGORIE,
                                       latitude, longitude, distance, categorie]];
    
    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];

}

- (void) fetchLocationsWithDistance: (float)distance andLongitude : (float)longitude andLatitude : (float)latitude andDelegate:(id)sender
{
    self.delegate = sender;
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:URL_TOUT_LES_LIEUX,
                                                latitude, longitude, distance]];
    
    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void) insertLocation:(Lieu*) leLieu{
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:URL_AJOUT_LIEU,
                                       [leLieu _nom],
                                       [leLieu _categorie],
                                       [leLieu _latitude],
                                       [leLieu _longitude]]];
    
    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [[NSURLConnection alloc] initWithRequest:request delegate:nil];
}

#pragma mark -
#pragma mark delegatefunctions

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // Show error
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //On converti notre flux en NSDictionary (via le JSON adapter)
    NSError* jsonError = nil;
    NSArray* array = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
    
    if (jsonError != nil) {
        NSLog(@"Erreur dans la fonction - fetchLocationsFromJson - lors de la creation de l\'array\n code erreur : %@", [jsonError description]);
    }
    
    if (!array || ![array isKindOfClass:[NSArray class]]) {
        NSLog(@"Le parsing du retour ne nous renvoi pas un nsarray...");
    }
        
    //traitement...
    NSArray* lieuArray = [Lieu lieuArrayFromNSDictionary:array];
    
    
    for (Lieu* tL in lieuArray) {
        NSLog(@"\n%@", [tL description]);
    }
    
    NSLog(@"\n\n\n\n");
    
    [delegate finishWithData:lieuArray];
}


#pragma mark -
#pragma mark Singleton

+ (TMServerApi *)sharedInstance {
	if (!sharedInstance) {
		sharedInstance = [[super allocWithZone:NULL] init];
	}
	
	return sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone {
	return [[self sharedInstance] retain];
}

- (id)copyWithZone:(NSZone *)zone {
	return self;
}

- (id)retain {
	return self;
}

- (NSUInteger)retainCount {
	return NSUIntegerMax;
}

- (oneway void)release { }

- (id)autorelease {
	return self;
}
@end
